package com.kgcx.price.utils;


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpRequestUtil {
	static String proxyHost = "127.0.0.1";
	static int proxyPort = 8080;
	
	/**
	 * 通过get方式发送请求，默认跳过NULL值，即不发送value=null的key
	 * 
	 * @param url
	 * @param params
	 *            参数
	 * @return
	 * @throws Exception
	 */
	public static String sendRequestByGet(String url, Map<String, Object> params) throws IOException {
		return sendRequestByGet(url, params, false);
	}

	/**
	 * 通过get方式发送请求
	 * 
	 * @param url
	 * @param params
	 *            参数
	 * @param skipNull
	 *            是否跳过NULL值，true则不发送value=null的key，否则发送value=
	 * @return
	 * @throws Exception
	 */
	public static String sendRequestByGet(String url, Map<String, Object> params, boolean skipNull) throws IOException {
		if (null == url || "".equals(url.trim())) {
			throw new IOException("url is null...");
		}
		OutputStreamWriter out = null;
		BufferedReader in = null;
		StringBuilder connResult = new StringBuilder("");
		String fullUrl = "";
		try {
			StringBuilder builder = new StringBuilder(url);
			if (null != params && params.size() > 0) {
				builder.append("?");
				for (String s : params.keySet()) {
					if (null == params.get(s)) {
						if (!skipNull) {
							builder.append(s).append("=").append("&");
						}
						continue;
					}
					if (params.get(s) instanceof Iterable<?>) {
						Iterable<?> ite = (Iterable<?>) params.get(s);
						for (Object i : ite) {
							builder.append(s).append("=").append(i).append("&");
						}
					} else {
						builder.append(s).append("=").append(params.get(s)).append("&");
					}
				}
				builder.delete(builder.length() - 1, builder.length());
			}
			fullUrl = builder.toString();
			log.debug(String.format("http request %s", fullUrl));
			URL destURL = new URL(builder.toString());
			HttpURLConnection urlConn = (HttpURLConnection) destURL.openConnection();
			urlConn.setConnectTimeout(5000);
			urlConn.setReadTimeout(40000);
			urlConn.setDoOutput(true);
			urlConn.setDoInput(true);
			urlConn.setAllowUserInteraction(false);
			urlConn.setUseCaches(false);
			urlConn.setRequestMethod("GET");
			urlConn.connect();
			
			// 响应编码
			String contentType = urlConn.getHeaderField("Content-Type");
			String encode = "uft-8";
			int index = -1;
			if (null != contentType && (index = contentType.indexOf("charset=")) > -1) {
				encode = contentType.substring(index + 8);
			}
			// 返回状态码
			int state = urlConn.getResponseCode();
			if (state < 400) {// 返回状态码<400为正确响应
				in = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "utf-8"));
			} else {
				in = new BufferedReader(new InputStreamReader(urlConn.getErrorStream(), "utf-8"));
			}
			String s = null;
			while ((s = in.readLine()) != null) {
				connResult.append(s);
			}
			log.debug(String.format("http request %s, response[code:%d, encode:%s, content:%s]", fullUrl, state,
					encode, connResult.toString()));
		} catch (IOException e) {
			log.error("http request[" + fullUrl + "] error", e);
			throw e;
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				log.error("http request[" + fullUrl + "] error", e);
				throw e;
			}
		}
		return connResult.toString();
	}

	/**
	 * 通过post方式发送请求，默认跳过NULL值，即不发送value=null的key
	 * 
	 * @param url
	 * @param params
	 *            参数
	 * @return
	 * @throws Exception
	 */
	public static String sendRequestByPost(String url, Map<String, Object> params) throws IOException {
		return sendRequestByPost(url, params, false);
	}

	/**
	 * 通过post方式发送请求
	 * 
	 * @param url
	 * @param params
	 *            参数
	 * @param skipNull
	 *            是否跳过NULL值，true则不发送value=null的key，否则发送value=
	 * @return
	 * @throws Exception
	 */
	public static String sendRequestByPost(String url, Map<String, Object> params, boolean skipNull) throws IOException {
		if (null == url || "".equals(url.trim())) {
			throw new IOException("url is null...");
		}
		OutputStreamWriter out = null;
		BufferedReader in = null;
		StringBuilder connResult = new StringBuilder("");
		String fullUrl = "";
		try {
			StringBuilder builder = new StringBuilder();
			if (null != params && params.size() > 0) {
				for (String s : params.keySet()) {
					if (null == params.get(s)) {
						if (!skipNull) {
							builder.append(s).append("=").append("&");
						}
						continue;
					}
					if (params.get(s) instanceof Iterable<?>) {
						Iterable<?> ite = (Iterable<?>) params.get(s);
						for (Object i : ite) {
							builder.append(s).append("=").append(i).append("&");
						}
					} else {
						builder.append(s).append("=").append(params.get(s)).append("&");
					}
				}
				builder.delete(builder.length() - 1, builder.length());
			}
			fullUrl = url + "?" + builder.toString();
			System.out.println(fullUrl+"..");
			log.debug(String.format("http request %s", fullUrl));
			URL destURL = new URL(url);
			HttpURLConnection urlConn = (HttpURLConnection) destURL.openConnection();
			urlConn.setConnectTimeout(5000);
			urlConn.setReadTimeout(40000);
			urlConn.setDoOutput(true);
			urlConn.setDoInput(true);
			urlConn.setAllowUserInteraction(false);
			urlConn.setUseCaches(false);
			urlConn.setRequestMethod("POST");
			OutputStream oups = urlConn.getOutputStream();
			oups.write(builder.toString().getBytes());
			urlConn.connect();
			// 响应编码
			String contentType = urlConn.getHeaderField("Content-Type");
			String encode = "UTF-8";
			int index = -1;
			if (null != contentType && (index = contentType.indexOf("charset=")) > -1) {
				encode = contentType.substring(index + 8);
			}
			// 返回状态码
			int state = urlConn.getResponseCode();
			if (state < 400) {// 返回状态码<400为正确响应
				in = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), encode));
			} else {
				in = new BufferedReader(new InputStreamReader(urlConn.getErrorStream(), encode));
			}
			String s = null;
			while ((s = in.readLine()) != null) {
				connResult.append(s);
			}
			log.debug(String.format("http request %s, response[code:%d, encode:%s, content:%s]", fullUrl, state,
					encode, connResult.toString()));
			System.out.println(String.format("http request %s, response[code:%d, encode:%s, content:%s]", fullUrl, state,
					encode, connResult.toString()));
		} catch (IOException e) {
			log.error("http request[" + fullUrl + "] error", e);
			throw e;
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				log.error("http request[" + fullUrl + "] error", e);
				throw e;
			}
		}
		return connResult.toString().trim();
	}

	public static String sendRequest(String url, Map<String, Object> params) throws Exception {
		OutputStreamWriter out = null;
		BufferedReader in = null;
		StringBuilder connResult = new StringBuilder("");
		try {
			StringBuilder builder = new StringBuilder(url).append("?");
			for (String s : params.keySet()) {
				if (null == params.get(s)) {
					continue;
				}
				if (params.get(s) instanceof Iterable<?>) {
					Iterable<?> ite = (Iterable<?>) params.get(s);
					for (Object i : ite) {
						builder.append(s).append("=").append(i).append("&");
					}
				} else {
					builder.append(s).append("=").append(params.get(s)).append("&");
				}
			}
			builder.delete(builder.length() - 1, builder.length());
			log.info(String.format("http request %s", builder));
			URL destURL = new URL(builder.toString());
			HttpURLConnection urlConn = (HttpURLConnection) destURL.openConnection();
			urlConn.setConnectTimeout(5000);
			urlConn.setReadTimeout(40000);
			urlConn.setDoOutput(true);
			urlConn.setDoInput(true);
			urlConn.setAllowUserInteraction(false);
			urlConn.setUseCaches(false);
			urlConn.setRequestMethod("GET");
			urlConn.connect();
			in = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
			String s = null;
			while ((s = in.readLine()) != null) {
				connResult.append(s);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return connResult.toString().trim();
	}
	
	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @param isproxy
	 *            是否使用代理模式
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param, boolean isproxy) {
		OutputStreamWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			HttpURLConnection conn = null;
			if (isproxy) {// 使用代理模式
				@SuppressWarnings("static-access")
				Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort));
				conn = (HttpURLConnection) realUrl.openConnection(proxy);
			} else {
				conn = (HttpURLConnection) realUrl.openConnection();
			}
			// 打开和URL之间的连接

			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST"); // POST方法

			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "application/json");

			conn.connect();

			// 获取URLConnection对象对应的输出流
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			// 发送请求参数
			out.write(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			result=new String(result.getBytes("ISO-8859-1"),"utf-8"); 
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
	 public static String sendGetTwo(String url, String param) {  
	        String result = "";  
	        BufferedReader in = null;  
	        try {  
	            String urlName = url + "?" + param;  
	            URL realUrl = new URL(urlName);  
	            //打开和URL之间的连接  
	            URLConnection conn = realUrl.openConnection();  
	            //设置通用的请求属性  
	            conn.setRequestProperty("accept", "*/*");  
	            conn.setRequestProperty("connection", "Keep-Alive");  
	            conn.setRequestProperty("user-agent",  
	                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");  
	        	conn.setRequestProperty("Content-Type", "application/json");
	            //建立实际的连接  
	            conn.connect();  
	            //获取所有响应头字段  
	            Map < String, List < String >> map = conn.getHeaderFields();  
	            //遍历所有的响应头字段  
	            for (String key: map.keySet()) {  
	                System.out.println(key + "--->" + map.get(key));  
	            }  
	            //定义BufferedReader输入流来读取URL的响应  
	            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
	            String line;  
	            while ((line = in .readLine()) != null) {  
	                result += "/n" + line;  
	            }  
	        } catch (Exception e) {  
	            System.out.println("发送GET请求出现异常！" + e);  
	            e.printStackTrace();  
	        }  
	        //使用finally块来关闭输入流  
	        finally {  
	            try {  
	                if ( in != null) { in .close();  
	                }  
	            } catch (IOException ex) {  
	                ex.printStackTrace();  
	            }  
	        }  
	        return result;  
	    }  
	    /**  
	     * 向指定URL发送POST方法的请求  
	     * @param url 发送请求的URL  
	     * @param param 请求参数，请求参数应该是name1=value1&name2=value2的形式。  
	     * @return URL所代表远程资源的响应  
	     */  
	    public static String sendPost(String url, String param) {  
	    	
 	    	PrintWriter out = null;  
	        BufferedReader in = null;  
	        String result = "";  
	        try {  
	            URL realUrl = new URL(url);  
	            //打开和URL之间的连接  
	            URLConnection conn = realUrl.openConnection();  
	            //设置通用的请求属性  
	            conn.setRequestProperty("accept", "*/*");  
	            conn.setRequestProperty("connection", "Keep-Alive");  
	            conn.setRequestProperty("user-agent",  
	                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); 
	        	conn.setRequestProperty("Content-Type", "application/json");
	            //发送POST请求必须设置如下两行  
	            conn.setDoOutput(true);  
	       /*     conn.setDoInput(true);  
	            //转码
	            String encode = URLEncoder.encode(param, "utf-8");
	            //解码
	            String decode = URLDecoder.decode(encode,"utf-8");	*/ 
	            //获取URLConnection对象对应的输出流  
	            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));  
	            //发送请求参数  
	   
	            out.print(param); 
	            //flush输出流的缓冲  
	            out.flush();  
	            //定义BufferedReader输入流来读取URL的响应  
	            in = new BufferedReader(  
	                new InputStreamReader(conn.getInputStream(),"utf-8"));  
	            String line;  
	            while ((line = in .readLine()) != null) {  
	                result +=  line;  
	            }  
	                  
	        } catch (Exception e) {  
	            System.out.println("发送POST请求出现异常！" + e);  
	            e.printStackTrace();  
	        }  
	        //使用finally块来关闭输出流、输入流  
	        finally {  
	            try {  
	                if (out != null) {  
	                    out.close();  
	                }  
	                if ( in != null) { in .close();  
	                }  
	            } catch (IOException ex) {  
	                ex.printStackTrace();  
	            }  
	        }  
	        
	    
	        return result;  
	    }  
	    
	    public static String Post(String URL,String SendData) {
	    	String  urlStr = URL;
	    	String send = SendData;
	    	StringBuilder str = null ;
	    	try {
	    		
	    		URL url = new URL(urlStr);
	    		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

	    		conn.setRequestMethod("POST");
	    		conn.setDoOutput(true);
	    		conn.setDoInput(true);
	    		conn.setConnectTimeout(10000);
	    		conn.setReadTimeout(10000);
	    		conn.setRequestProperty("Connection", "keep-alive");

	    		conn.connect();

	    		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
	    		out.write(send.getBytes());
	    		out.flush();
	    		out.close();

	    		InputStream in = conn.getInputStream();

	    		BufferedReader buffer = new BufferedReader(new InputStreamReader(in));

	    		String s;
	    		str = new StringBuilder();

	    		while ((s = buffer.readLine()) != null) {
	    			str.append(s);
	    		}
               
	    		System.out.print(conn.getResponseCode() + "\n" + str.toString());


	    	} catch (Exception e) {
	    		e.printStackTrace();
	    	}
			return str.toString();

	    }
	  
}
